package com.example.summary.sort;

import com.alibaba.fastjson.JSON;

/**
 * Created by wzn on 2019/1/5.
 */

/**
 * 从第i=1个开始，分别和前面的对比,依次向后移动，然后如果找到位置则插入
 */
public class Insert {
    public static void main(String[] args) {
        int[] x = {9, 7, 3, 10, 11, 23, 4, 8, 1};

        sort2(x);

        System.out.println(JSON.toJSONString(x));
    }

    private static void sort(int[] x) {
        for (int i = 1; i < x.length; i++) {
            int temp = x[i];
            int leftindex = i - 1;

            while (leftindex >= 0 && temp < x[leftindex]) {
                x[leftindex + 1] = x[leftindex];
                leftindex--;
            }
            x[leftindex + 1] = temp;
        }
    }

    private static void sort2(int[] x) {
        for (int i = 1; i < x.length; i++) {
            int temp = x[i];
            int leftindex = i;

            while (leftindex - 1 >= 0 && temp < x[leftindex - 1]) {
                x[leftindex] = x[leftindex-1];
                leftindex--;
            }

            x[leftindex] = temp;
        }
    }

}
